package cn.wwcyc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.wwcyc.domain.TjDw;
import cn.wwcyc.service.TjDwService;
import cn.wwcyc.mapper.TjDwMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Stack;

/**
* @author aa
* @description 针对表【TJ_DW】的数据库操作Service实现
* @createDate 2024-03-08 10:36:56
*/
@Service
public class TjDwServiceImpl extends ServiceImpl<TjDwMapper, TjDw>
    implements TjDwService{
    @Autowired
    TjDwMapper tjDwMapper;
    @Override
    public TjDw getDwTreeById(Long dwid){
        TjDw root = tjDwMapper.selectById(dwid);
        LambdaQueryWrapper<TjDw> qw = new LambdaQueryWrapper();
        qw.eq(TjDw::getPid, dwid);
        List<TjDw> list = tjDwMapper.selectList(qw);
        root.setChildren(list);
        for(TjDw tjDw : list){
            addChildren(tjDw);
        }
        return root;
    }

    @Override
    public List<TjDw> DwTreeToList(List<TjDw> tjDwList, TjDw root) {
        if(root == null){
            return tjDwList;
        }
        tjDwList.add(root);
        if(root.getChildren()!=null && root.getChildren().size()>0){
            for(TjDw tjDw : root.getChildren()){
                DwTreeToList(tjDwList, tjDw);
            }
        }
        return tjDwList;
    }

    @Override
    public List<Long> getPathByid(Long id) {
        if(id==null)
            return null;
        Stack<Long> path = new Stack<>();
        List<Long> pathList = new java.util.ArrayList<>();
        path.push(id);
        TjDw dw = tjDwMapper.selectById(id);
        while (dw!=null && dw.getPid()!=null){
            dw = tjDwMapper.selectById(dw.getPid());
            path.push(dw.getId());
        }
        while(!path.isEmpty()){
            pathList.add(path.pop());
        }
        return pathList;
    }

    private void addChildren(TjDw tjDw) {
        LambdaQueryWrapper<TjDw> qw1 = new LambdaQueryWrapper();
        qw1.eq(TjDw::getPid, tjDw.getId());
//        qw1.orderByAsc(Menu::getXh);
        List<TjDw> tjDwList = tjDwMapper.selectList(qw1);
        if(tjDwList == null || tjDwList.size() == 0){
            return;
        }else{
            tjDw.setChildren(tjDwList);
            for(TjDw tjDw1 : tjDwList){
                addChildren(tjDw1);
            }
        }
    }
}




